<template>
  <div class="login-page mx-auto p-3 max-w-330">
    <h5 class="my-4 text-center">登录</h5>
    <validate-form @form-submit="onFormSubmit">
      <div class="mb-3">
        <label class="form-label">邮箱地址</label>
        <validate-input
          :rules="emailRules"
          v-model="emailVal"
          placeholder="请输入邮箱地址"
          type="text"
        />
      </div>
      <div class="mb-3">
        <label class="form-label">密码</label>
        <validate-input
          :rules="passwordRules"
          v-model="passwordVal"
          placeholder="请输入密码"
          type="password"
        />
      </div>
      <template #submit>
        <button class="btn btn-primary">登录</button>
      </template>
    </validate-form>
  </div>
</template>

<script lang='ts'>
import { defineComponent, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
import ValidateInput, { RulesProp } from '../components/ValidateInput.vue'
import ValidateForm from '../components/ValidateForm.vue'
import createMessage from '../components/createMessage'

export default defineComponent({
  components: {
    ValidateInput,
    ValidateForm
  },
  setup () {
    const router = useRouter()

    const store = useStore()

    const emailVal = ref('')
    const emailRules: RulesProp = [
      {
        type: 'required',
        message: '邮箱地址不能为空'
      },
      {
        type: 'email',
        message: '请输入正确的邮箱格式'
      }
    ]

    const passwordVal = ref('')
    const passwordRules: RulesProp = [
      {
        type: 'required',
        message: '密码不能为空'
      },
      {
        type: 'custom',
        message: '密码不得小于六位数',
        validator () {
          return Promise.resolve(passwordVal.value.length >= 6)
        }
      }
    ]

    const onFormSubmit = (result: boolean) => {
      if (result) {
        const payload = {
          email: emailVal.value,
          password: passwordVal.value
        }

        store.dispatch('login', payload).then(() => {
          store.dispatch('fetchCurrentUser')

          createMessage('success', '登录成功，2秒后跳转至首页', 2000)

          setTimeout(() => {
            router.push({
              name: 'home'
            })
          }, 2000)
        })
      }
    }

    return {
      emailRules,
      emailVal,
      passwordVal,
      passwordRules,
      onFormSubmit
    }
  }
})
</script>
